<template>
	<view class="order-list-container">
		
		<!-- 订单列表 -->
		<view class="order-list">
			<view class="empty-orders" v-if="!hasOrders">
				<text class="empty-text">暂无订单记录</text>
			</view>
			
			<view class="order-item" v-for="order in orders" :key="order.id" @tap="viewOrderDetail(order.orderNumber)">
				<view class="order-header">
					<view class="order-id-section">
						<text class="order-id">订单号：{{order.orderNumber}}</text>
						<text class="order-user" v-if="order.userName">用户：{{order.userName}}</text>
					</view>
					<text class="order-status">{{getOrderStatusText(order.status)}}</text>
				</view>
				<!-- 订单商品信息 -->
				<view class="order-info">
					<text class="order-count">共{{order.items ? order.items.length : 0}}件商品</text>
				</view>
				<view class="order-footer">
					<text class="order-time">{{formatDate(order.createdAt)}}</text>
					<view class="order-actions">
						<button 
							class="action-btn" 
							v-if="order.status === 'unpaid'"
							@tap.stop="markAsPaid(order.orderNumber)"
						>标记已付款</button>
						<button 
							class="action-btn" 
							v-if="order.status === 'unshipped'"
							@tap.stop="markAsShipped(order.orderNumber)"
						>标记已发货</button>
						<button 
							class="action-btn cancel-btn" 
							v-if="order.status === 'unpaid'"
							@tap.stop="cancelOrder(order.orderNumber)"
						>取消订单</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="hasOrders && hasMoreOrders">
			<text class="load-more-text" @tap="loadMoreOrders">点击加载更多</text>
		</view>
		<view class="load-more" v-if="hasOrders && !hasMoreOrders">
			<text class="load-more-text">已加载全部订单</text>
		</view>
	</view>
</template>

<script>
	import { orderApi } from '../../api/index.js';
	
	export default {
		data() {
			return {
				currentType: 'all', // 当前显示的订单类型
				orders: [], // 订单列表
				hasOrders: false, // 是否有订单
				hasMoreOrders: false, // 是否有更多订单
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页显示条数
				orderTypes: [
					{ name: '全部订单', type: 'all' },
					{ name: '待付款', type: 'unpaid' },
					{ name: '待发货', type: 'unshipped' },
					{ name: '待收货', type: 'unreceived' },
					{ name: '待评价', type: 'unrated' }
				],
				loading: false // 是否正在加载
			}
		},
		onLoad(options) {
			// 如果有传入类型参数，设置当前类型
			if (options.type) {
				this.currentType = options.type;
			}
			
			// 加载订单
			this.getOrders();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 切换订单类型
			switchOrderType(type) {
				if (this.currentType === type) return;
				
				this.currentType = type;
				this.currentPage = 1;
				this.orders = [];
				this.getOrders();
			},
			
			// 获取订单列表
			async getOrders() {
				if (this.loading) return;
				
				this.loading = true;
				
				try {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					
					const res = await orderApi.getAllOrders({
						page: this.currentPage,
						limit: this.pageSize,
						status: this.currentType === 'all' ? '' : this.currentType
					});
					
					console.log('获取所有订单列表:', res);
					
					if (res.code === 200) {
						// 如果是第一页，直接赋值；如果不是第一页，追加数据
						if (this.currentPage === 1) {
							this.orders = res.data.items;
						} else {
							this.orders = [...this.orders, ...res.data.items];
						}
						
						this.hasOrders = this.orders.length > 0;
						
						// 判断是否有更多数据
						this.hasMoreOrders = res.data.totalPages > this.currentPage;
					} else {
						uni.showToast({
							title: res.message || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取订单失败:', error);
					uni.showToast({
						title: '获取订单失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
					this.loading = false;
				}
			},
			
			// 加载更多订单
			loadMoreOrders() {
				if (this.loading || !this.hasMoreOrders) return;
				
				this.currentPage++;
				this.getOrders();
			},
			
			// 查看订单详情
			viewOrderDetail(orderNumber) {
				uni.navigateTo({
					url: `/pages/order/confirmation?orderId=${orderNumber}&isAdmin=true`
				});
			},
			
			// 标记订单已付款
			markAsPaid(orderNumber) {
				uni.showModal({
					title: '确认操作',
					content: '确认将此订单标记为已付款？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...',
									mask: true
								});
								
								const response = await orderApi.markAsPaid(orderNumber);
								
								if (response.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '已标记为已付款',
										icon: 'success'
									});
									
									// 刷新订单列表
									this.currentPage = 1;
									this.orders = [];
									this.getOrders();
								} else {
									uni.hideLoading();
									uni.showToast({
										title: response.message || '操作失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('标记已付款失败:', error);
								uni.hideLoading();
								uni.showToast({
									title: '操作失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 标记订单已发货
			markAsShipped(orderNumber) {
				uni.showModal({
					title: '确认操作',
					content: '确认将此订单标记为已发货？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...',
									mask: true
								});
								
								const response = await orderApi.markAsShipped(orderNumber);
								
								if (response.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '已标记为已发货',
										icon: 'success'
									});
									
									// 刷新订单列表
									this.currentPage = 1;
									this.orders = [];
									this.getOrders();
								} else {
									uni.hideLoading();
									uni.showToast({
										title: response.message || '操作失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('标记已发货失败:', error);
								uni.hideLoading();
								uni.showToast({
									title: '操作失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 取消订单
			cancelOrder(orderNumber) {
				uni.showModal({
					title: '确认操作',
					content: '确认取消此订单？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...',
									mask: true
								});
								
								const response = await orderApi.cancelOrder(orderNumber);
								
								if (response.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '订单已取消',
										icon: 'success'
									});
									
									// 刷新订单列表
									this.currentPage = 1;
									this.orders = [];
									this.getOrders();
								} else {
									uni.hideLoading();
									uni.showToast({
										title: response.message || '操作失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('取消订单失败:', error);
								uni.hideLoading();
								uni.showToast({
									title: '操作失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 获取订单状态文本
			getOrderStatusText(status) {
				switch (status) {
					case 'unpaid':
						return '待付款';
					case 'unshipped':
						return '待发货';
					case 'unreceived':
						return '待收货';
					case 'unrated':
						return '待评价';
					default:
						return '已完成';
				}
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				
				// 将日期字符串格式化为更友好的格式，包含时分秒
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}
		}
	}
</script>

<style>
	.order-list-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 30rpx;
	}
	
	.page-header {
		background-color: #F3B250;
		padding: 30rpx 20rpx;
		display: flex;
		align-items: center;
		position: relative;
	}
	
	.back-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.back-arrow {
		color: #fff;
		font-size: 40rpx;
		font-weight: bold;
	}
	
	.page-title {
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		flex: 1;
		text-align: center;
		margin-right: 60rpx; /* 为了平衡左边的返回按钮，保持标题居中 */
	}
	
	.order-types {
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		padding: 20rpx 10rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.type-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 20%;
		padding: 10rpx 0;
	}
	
	.type-item.active {
		font-weight: bold;
	}
	
	.type-item.active .type-name {
		color: #F3B250;
	}
	
	.type-name {
		font-size: 24rpx;
		color: #333;
	}
	
	.order-list {
		padding: 0 20rpx;
	}
	
	.empty-orders {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 0;
		background-color: #fff;
		border-radius: 12rpx;
		margin-top: 20rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	
	.order-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}
	
	.order-id-section {
		display: flex;
		flex-direction: column;
	}
	
	.order-id {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.order-user {
		font-size: 24rpx;
		color: #666;
	}
	
	.order-status {
		font-size: 26rpx;
		color: #F3B250;
		font-weight: 500;
	}
	
	.order-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.order-count {
		font-size: 26rpx;
		color: #666;
	}
	
	.order-total {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
	}
	
	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #f5f5f5;
	}
	
	.order-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.order-actions {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 30rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		background-color: #fff;
		color: #F3B250;
		border: 1rpx solid #F3B250;
	}
	
	.cancel-btn {
		color: #666;
		border: 1rpx solid #666;
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.load-more-text {
		font-size: 26rpx;
		color: #999;
	}
</style> 